package com.itcast.rabbitmq.routing;

import com.itcast.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @ClassName Rec2
 * @Description 路由模式更新接受者2
 * @Author Trigger Wu
 * @Date 2018/9/2811:14
 * @Version 1.0
 **/

public class Rec2 {



    private final static String QUEUE_NAME = "test_queue_direct_2";

    private final static String EXCHANGE_NAME = "test_exchange_direct";

    public static void main(String[] argv) throws Exception {

        // 获取到连接以及mq通道
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        // 绑定队列到交换机
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "insert");
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"update");
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"delete");

        // 同一时刻服务器只会发一条消息给消费者
        channel.basicQos(1);

        // 定义队列的消费者
        channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel) {
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body)
                    throws IOException {
                String routingKey = envelope.getRoutingKey();
                //获取内容
                String contentType = properties.getContentType();
                //确认消息的位置,index
                long deliveryTag = envelope.getDeliveryTag();

                String message = new String(body);
                System.out.println(" [搜索系统] '" + message + "'");
                //休眠
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 返回确认状态
                channel.basicAck(deliveryTag, false);
            }
        });
    }
}
